package com.bookmanager.www.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bookmanager.www.common.DTO.AdminDTO;
import com.bookmanager.www.common.PO.AdminMenuListPO;
import com.bookmanager.www.common.utils.Result;
import com.bookmanager.www.entity.EndRole;
import com.bookmanager.www.entity.FlBookOrder;
import com.bookmanager.www.entity.FlUser;
import com.bookmanager.www.mapper.FlBookMapper;
import com.bookmanager.www.mapper.FlBookorderMapper;
import com.bookmanager.www.mapper.FlUserMapper;
import com.bookmanager.www.service.FlUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.models.security.SecurityScheme;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.PrecisionMetric;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: 风离
 * @Date: 2021/11/14/18:09
 * @Description:
 */
@RestController
@RequestMapping("/fl-admin")
@Slf4j
@RequiresRoles(value = {"superAdmin","超级管理员"},logical = Logical.OR)
@Api(tags = "超级管理员管理")
public class SuperAdminController {

    @Resource
    FlBookorderMapper flBookOrderMapper;
    @Resource
    FlBookMapper flBookMapper;
    @Resource
    FlUserService flUserService;
    @Resource
    FlUserMapper flUserMapper;
    /**
     * 可创建管理员 删除管理员 管理管理员
     * 可删除订单
     * 可删除图书 给图书增加或减少库存 图书上下架
     * 可删除分类及分类下图书
     * 用户/管理员 禁封/解封
     * 修改轮播图信息
     * 发布公告
     * 路由权限管理
     *
     */

   @PostMapping("/searchRoleMenu")
   @RequiresRoles(value ={"superAdmin","超级管理员"},logical = Logical.OR)
   @ApiOperation("查看角色菜单")
   Result searchRoleMenu(@RequestParam("roleId")String roleId)
   {
          List<Integer> menuIdList = flUserMapper.getMenuIdList(roleId);

       return Result.succ("查看角色菜单成功",menuIdList);
   }

   @PostMapping("/changeAdminDetail")
   @RequiresRoles(value ={"superAdmin","超级管理员"},logical = Logical.OR)
   @ApiOperation("修改管理员信息")
   Result changeAdminDetail(@RequestBody @Validated AdminDTO adminDTO)
   {



       return Result.succ();
   }




    @PostMapping("/roleAssignment")
    @RequiresRoles(value ={"superAdmin","超级管理员"},logical = Logical.OR)
    @ApiOperation("角色分配")
    Result roleAssignment(@RequestParam("userId")String userId,@RequestParam("roleId")String roleId)
    {
        List<EndRole> endRoleList = flUserMapper.getEndRolesList();
        int count = 0;
        for (EndRole endRole : endRoleList) {
            if(endRole.getId()==Integer.parseInt(roleId))
            {
                count++;
            }
        }
        if(count==0)
        {
            return Result.fail("角色分配失败 该角色id不存在！！","");
        }


        int update = flUserMapper.updateRoleId(userId,roleId);
        if(update!=0)
        {
            return Result.succ("角色分配成功","");
        }
        return Result.fail("角色分配失败","");
    }



    @GetMapping("/getAdminMenu")
    @RequiresRoles(value = {"superAdmin","超级管理员"},logical = Logical.OR)
    @ApiOperation("获取管理员菜单")
    Result getAdminMenu(){

        List<AdminMenuListPO> adminMenuListPO = flUserMapper.getAdminMenuList();

        return Result.succ("获取管理员菜单列表成功",adminMenuListPO);
    }




    @DeleteMapping("/deleteBatchOrder")
    @RequiresRoles(value = {"superAdmin","超级管理员"},logical = Logical.OR)
    @ApiOperation(value = "批量或者单个删除订单")
    Result deleteBatchOrder(@RequestParam("batchIds")String[] orderIds)
    {
        log.warn("批量删除订单开始====>");
        for(int i=0;i<orderIds.length;i++)
        {
            int deleteOrder = flBookOrderMapper.deleteOrderByOrderId(orderIds[i]);
            if(deleteOrder!=0)
            {
                log.warn("删除订单成功 当前剩余待删除订单数==【"+(orderIds.length-1-i)+"】");
            }
        }
        return Result.succ("批量删除成功","");
    }


    @PutMapping("/createAdmin")
    @RequiresRoles(value = {"superAdmin","超级管理员"},logical = Logical.OR)
    @ApiOperation(value = "创建管理员账号")
    Result createAdmin(@RequestParam("username")String username,@RequestParam("password")String password)
    {
        int roleId=1;
        int insert = flUserService.registerAdmin(username,password,roleId);
        if(insert!=0)
        {
            return Result.succ("创建管理员账号成功","");
        }

          return Result.fail("插入数据库失败！！","");
    }


    @GetMapping("/getAllAdminDetail")
    @ApiOperation(value = "获取所有管理员信息",notes = "需要超级管理员身份")
    @RequiresRoles(value = {"superAdmin","超级管理员"},logical = Logical.OR)
    public Result getAllAdminDetail(@RequestParam("page")Integer page,
                                    @RequestParam("pageSize")Integer pageSize)
    {
        Page<FlUser> p =new Page<>(page,pageSize);
        FlUser flUser = new FlUser();
        IPage<FlUser> userDetailList = p.setRecords(flUserMapper.selectRoleUser(p,flUser,1));

        return Result.succ("获取管理员信息成功！！",userDetailList);
    }

    @DeleteMapping("/deleteBatchAdminOrUser")
    @ApiOperation(value = "删除批量/单个（管理员/用户）",notes = "需要超级管理员身份")
    @RequiresRoles(value = {"superAdmin","超级管理员"},logical = Logical.OR)
    public Result deleteBatchAdmin(@RequestParam("adminIds") String[] adminIds)
    {
        for (String adminId : adminIds) {
            int delete = flUserMapper.deleteBatchAdmin(adminId);
            if(delete!=0)
            {
                log.warn("删除用户+1");
            }
        }
        return Result.succ("批量删除成功！！","");
    }

    @PostMapping("/changeUserStatus")
    @ApiOperation(value = "（禁封/解封）批量/单个（管理员/用户）",notes = "需要超级管理员身份")
    @RequiresRoles(value = {"superAdmin","超级管理员"},logical = Logical.OR)//记得在登录的时候首先校验账号是否异常
    public Result changeUserStatus(@RequestParam("users")String[] users,@RequestParam("status")Integer status)
    {
        if(status!=0&&status!=1)
        {
            return Result.fail("状态传入有误！！","");
        }
        for (String user : users) {
            int update = flUserMapper.changeUserStatusByUserId(user,status);
            if(update!=0)
            {
                log.warn("用户状态更新成功！！！");
            }
        }

        return Result.succ("批量更新用户状态成功！！","");
    }


    @PostMapping("/changeStock")
    @RequiresRoles(value = {"superAdmin","超级管理员"},logical = Logical.OR)
    @ApiOperation(value = "增加或者减少商品库存")
    Result changeStock(@RequestParam("bookId")String bookId, @RequestParam("newStock")Integer newStock)
    {
        int update = flBookMapper.changeStockByBookId(bookId,newStock);
        if(update!=0)
        {
            return Result.succ("更新库存 成功！！","");
        }

        return Result.fail("更新库存失败！！ 数据库更新失败！！","");

    }

    @PostMapping("/putOrPullBooks")
    @RequiresRoles(value = {"superAdmin","超级管理员"},logical = Logical.OR)
    @ApiOperation(value = "批量/单本图书上下架",notes = "type=0 批量上架 type=1 批量下架")
    Result putOrPullBooks(@RequestParam("bookIds")String[] bookIds,@RequestParam("type")Integer type)
    {
        if(type!=0&&type!=1)
        {
            return Result.fail("状态传入有误！！","");
        }

        for (String bookId : bookIds) {
            int update = flBookMapper.changeBookStatusByBookId(bookId,type);
            if(update!=0)
            {
                log.warn("改变状态成功！！！"+update);
            }

        }
        return Result.succ("批量操作成功！！！","");
    }



}
